package com.anti_poverty_detection_system.springboot.service.impl;

import com.anti_poverty_detection_system.springboot.mapper.RegionUpperMapper;
import com.anti_poverty_detection_system.springboot.model.Regions;
import com.anti_poverty_detection_system.springboot.service.IRegionsService;
import com.anti_poverty_detection_system.springboot.mapper.RegionsMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ZITONG BAI
 * @since 2024-06-17
 */
@Service
public class RegionsServiceImpl extends ServiceImpl<RegionsMapper, Regions> implements IRegionsService {
    @Autowired
    RegionsMapper regionsMapper;

    @Autowired
    RegionUpperMapper regionUpperMapper;
    public Regions getRegionsByRegionNumber(String regionNumber) {
        QueryWrapper<Regions> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("region_number", regionNumber);
        return regionsMapper.selectOne(queryWrapper);
    }

    public Regions getRegionsByRegionName(String regionName){
        QueryWrapper<Regions> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("region_name",regionName);
        return regionsMapper.selectOne(queryWrapper);
    }

    public Regions getRegionsByVillage(String village) {
        QueryWrapper<Regions> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("village",village);
        return regionsMapper.selectOne(queryWrapper);
    }
    public boolean deleteRegionByRegionName(String regionName){
        QueryWrapper<Regions> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("region_name",regionName);
        int rows=regionsMapper.delete(queryWrapper);
        return rows>0;
    }



    // 获取行政区信息
    public Page<Regions> getRegions(Page<Regions> page) {
        return regionsMapper.selectPage(page, null);
    }
    // 获取搜索行政区信息
    public Page<Regions> getSearchRegions(Page<Regions> page,String keywords){
        return regionsMapper.selectSearchRegions(page,keywords);
    }

    public void addRegionUpper(Regions regions){
        // 插入时对村乡县的逻辑设计
        if(regions.getTownship()!=null && !regions.getTownship().isEmpty()){
            // 如果有乡，则县是乡的上级
            regionUpperMapper.insertRegionUpper( regions.getCounty(),regions.getTownship(), regions.getRegionNumber());
            if(regions.getVillage()!=null && !regions.getVillage().isEmpty()){
                // 如果还有村，则乡是村的上级
                regionUpperMapper.insertRegionUpper(regions.getTownship(),regions.getVillage(),regions.getRegionNumber());
            }
        }
    }

}
